package com.qdlc.p2p.biz.processor.task;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.processor.event.TppAutoTenderVauleEvent;
import com.qdlc.p2p.biz.service.BorrowService;
import com.qdlc.p2p.biz.service.TppInvestService;
import com.qdlc.p2p.biz.service.UserAutoTenderLogService;
import com.qdlc.p2p.common.core.queue.TaskProcessorException;
import com.qdlc.p2p.common.core.queue.ValueEvent;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.dal.dto.Borrow;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserAutoTenderLog;
import com.qdlc.p2p.dal.model.BorrowModel;
import com.qdlc.p2p.dal.model.UserAutoTenderLogModel;


/**
 * 自动投标代收回调
 * @author linya 2015-12-30
 */
@Service
public class TppAutoTenderTaskProcessor extends AbstractTaskProcessor {

	private static final Logger logger = Logger.getLogger(TppAutoTenderTaskProcessor.class);
	
	@Resource
	TppInvestService tppInvestService;
	
	@Resource
	UserAutoTenderLogService userAutoTenderLogService;
	
	@Resource
	BorrowService borrowService;
	
	@Override
	public boolean supports(ValueEvent event) {
		return event instanceof TppAutoTenderVauleEvent;
	}

	@Override
	public void process0(ValueEvent event) throws TaskProcessorException {
		TppAutoTenderVauleEvent borrowEvent = (TppAutoTenderVauleEvent)event;
		BorrowModel borrowModel = borrowEvent.getBorrowModel();
		double money = borrowEvent.getMoney();
		double autoTenderMaxAcount = borrowEvent.getAutoTenderMaxAcount();
		Borrow borrow = borrowEvent.getBorrow();
		User user = borrowEvent.getUser();
		logger.info("代收投资金(1001)业务队列处理(自动投标代收回调后) START 订单号[" + borrowModel.getTenderBilNo() + "]");
		try {
			tppInvestService.tppAutoTender(money, autoTenderMaxAcount, borrow, user);
		} catch (Exception e) {
			logger.info("代收投资金(1001)业务队列处理异常  订单号[" + borrowModel.getTenderBilNo() + "]");
			logger.error(e.getMessage(), e);
			//如果自动投标出现异常，那么插入自动投标失败记录
			if(user != null && borrow != null){
				UserAutoTenderLog userAutoTenderLog = new UserAutoTenderLog();
				userAutoTenderLog.setUser(user);
				userAutoTenderLog.setBorrow(borrow);
				userAutoTenderLog.setAddTime(DateUtil.getNow());
				userAutoTenderLog.setStatus(UserAutoTenderLogModel.TENDER_FAIL);
				userAutoTenderLog.setRemark(MessageUtil.getMessage("MF105001011"));
				userAutoTenderLogService.save(userAutoTenderLog);
			}
		}finally {
			String isLastFlag = borrowEvent.getLastFlag();
			long borrowId = (borrow == null ? 0L : borrow.getId());
			if(isLastFlag.equals("lastFlag") && borrowId > 0){
				try{
					borrowService.updateStatus(borrowId, 1, 19);
				}catch(Exception e){
					logger.error(e.getMessage());
				}
			}
		}
		logger.info("代收投资金(1001)业务队列处理 END 订单号[" + borrowModel.getTenderBilNo() + "]");
	}

}
